package com.bjtu.douyin.utils.video;


import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;


import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class GrpcClient {
    private final ManagedChannel channel;
    private final VideoServiceGrpc.VideoServiceBlockingStub blockingStub;
    public GrpcClient(String host, int port) {
        this(ManagedChannelBuilder.forAddress(host, port).usePlaintext().defaultServiceConfig(createServiceConfig()).enableRetry());
    }

    public GrpcClient(ManagedChannelBuilder<?> channelBuilder) {
        channel = channelBuilder.build();
        blockingStub = VideoServiceGrpc.newBlockingStub(channel);
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    public List<Video> sendMessage(int userId, int count) {
        TopVideosRequest request = TopVideosRequest.newBuilder().setUserId(userId).setCount(count).build();
        TopVideosResponse response = blockingStub.getTopVideos(request);
        return response.getVideosList();
    }

    private static Map<String, Object> createServiceConfig() {
        return new HashMap<String, Object>() {{
            put("methodConfig", Collections.singletonList(
                    new HashMap<String, Object>() {{
                        put("name", Collections.singletonList(
                                new HashMap<String, Object>() {{
                                    put("service", "video_service.VideoService");  // 替换为你的服务名称
                                }}
                        ));
                        put("retryPolicy", new HashMap<String, Object>() {{
                            put("maxAttempts", 3.0);  // 最大重试次数，字符串形式
                            put("initialBackoff", "1s");  // 初始退避时间，设置为至少1秒
                            put("maxBackoff", "5s");  // 最大退避时间，设置为合理的值
                            put("backoffMultiplier", 1.0);  // 退避乘数
                            put("retryableStatusCodes", Collections.singletonList("UNAVAILABLE"));
                        }});
                    }}
            ));
        }};
    }

}
